package com.banzhi.shop.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.activity.GroupingDetailsActivity;
import com.banzhi.shop.adapter.GroupingAdapter;
import com.banzhi.shop.data.GroupingIndexBean;
import com.banzhi.shop.data.GroupsBean;
import com.banzhi.shop.model.CallBack.GroupingCallBack;
import com.banzhi.shop.model.Impl.GroupingImpl;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.VpSwipeRefreshLayout;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/13.
 */
//拼团精选
public class GroupingSelectFragment extends android.support.v4.app.Fragment implements GroupingCallBack, GroupingAdapter.OnItemClickListener {
    private GroupingImpl model;
    private int page = 1;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private GroupingIndexBean mDatabean;
    List<GroupsBean> mGroupsBeans = new ArrayList<>();
    // private BaseRecyclerAdapter<GroupsBean> mAdapter;
    private GroupingAdapter mAdapter;
    private List<GroupsBean> mGroups;
    private RelativeLayout mNoData;
    private Receivier mReceivier;
    //  private List<String> networkImages;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_grouping, container, false);
        initView(view);
        model = new GroupingImpl();
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData(page, 20, this);
        //注册广播接收者
        mReceivier = new Receivier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("Refresh");
        getActivity().registerReceiver( mReceivier, intentFilter);
        return view;
    }

    private void initView(View view) {
        mRefreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        mNoData = (RelativeLayout) view.findViewById(R.id.rl_nodata);
        //ImageView ivTop = (ImageView) view.findViewById(R.id.ivtop);

    }

    @Override
    public void ongetGroupingDataSuccess(Object object) {

        mDatabean = (GroupingIndexBean) object;
        //拼团数据
        mGroups = mDatabean.getGroups();
        if (page == 1) {
            mGroupsBeans.clear();
        } else {
            if (mGroups.size() == 0) {
                return;
            }
        }
        mGroupsBeans.addAll(mGroups);
        if (mGroupsBeans.size() == 0) {
            mNoData.setVisibility(View.VISIBLE);
        } else {
            mNoData.setVisibility(View.GONE);
        }
        ShowView();
        LoadingDialogUtils.dismiss();
    }

    private void ShowView() {
        mAdapter = new GroupingAdapter(mGroupsBeans);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
      //  setRefreshListener();
    }

    @Override
    public void onItemClick(View view, int position) {
        //  LogUtils.e("PPPPP",position+"");
        Intent intent = new Intent(getContext(), GroupingDetailsActivity.class);
        intent.putExtra("id", mGroupsBeans.get(position).getId());
        //   LogUtils.e("id" ,mGroupsBeans.get(position).getId());
        startActivity(intent);
    }

    private void setRefreshListener() {
        //设置 Header 为 MaterialHeader
        //    mRefreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        //设置 Footer 为 经典样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        mRefreshLayout.setHeaderHeight(60);//Header标准高度（显示下拉高度>=标准高度 触发刷新）
        mRefreshLayout.setPrimaryColorsId(R.color.backgroudColor, android.R.color.white);
        mRefreshLayout.setFooterHeight(60);//Footer标准高度（显示上拉高度>=标准高度 触发加载）
        // mRefreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        //  mRefreshLayout.autoRefresh(1000);//自动刷新
        //   mRefreshLayout.finishRefresh(1000);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //在这里执行上拉刷新时的具体操作(网络请求、更新UI等)
                page = 1;
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.getData(page, 20, GroupingSelectFragment.this);
                //清空集合
                mGroupsBeans.clear();
                //重新添加
                for (int i = 0; i < mGroups.size(); i++) {
                    mGroupsBeans.add(mGroups.get(i));
                }
                //刷新试图
                mAdapter.notifyDataSetChanged();
                refreshlayout.finishRefresh();

            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //网络请求到的数据
                page++;
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.getData(page, 20, GroupingSelectFragment.this);
                //试图获取总条目数
                int count = mAdapter.getItemCount();
                int size = mGroupsBeans.size();
                //如果当前试图总条目== 集合长度
                if (count == size) {
                    // Toast.makeText(getContext(), "数据以空", Toast.LENGTH_SHORT).show();
                }
                //当前试图总条目+20就是 一次加载20条目
                if (count + 20 < size) {
                    for (int i = count; i < (count + 20); i++) {
                        mGroupsBeans.add(mGroups.get(i));
                    }
                } else {
                    for (int i = count; i < size; i++) {
                        mGroupsBeans.add(mGroups.get(i));
                    }
                }
                mAdapter.notifyDataSetChanged();
                refreshlayout.finishLoadmore();
            }
        });
    }

    @Override
    public void ongetGroupingDataError(Object object) {
        LoadingDialogUtils.dismiss();
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
    public class Receivier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("Refresh".equals(action)) {
                setRefreshListener();
            }
        }
    }

    @Override
    public void onDestroy() {
        //注销广播接受者
        getActivity().unregisterReceiver(mReceivier);
        super.onDestroy();
    }
}
